<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card shadow="never">
        <!-- 标题 -->
          <div slot="header" class="clearfix">
            <span>试题录入</span>
          </div>
        <!-- 表单区域 -->
        <el-form ref="form" :model="form" label-width="110px" :rules="rules">
            <el-form-item label="学科" prop="subjectID">
              <el-select v-model="form.subjectID" placeholder="请选择"  class="selects">
                <el-option v-for="item in subjectListEasy" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="目录" prop="catalogID">
              <el-select v-model="form.catalogID" placeholder="请选择" class="selects" @focus="getcatalog">
                <el-option v-for="item in directoryListEasy" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="企业" prop="enterpriseID">
              <el-select v-model="form.enterpriseID" placeholder="请选择" class="selects">
                <el-option v-for="item in allCompanysList" :key="item.id" :label="item.company" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="城市" class="cityselect" prop="province">
              <el-select v-model="form.province" placeholder="请选择" @focus="randerFistCityList">
                <el-option v-for="item,index in fistCityList" :key="index" :label="item" :value="item"></el-option>
              </el-select>
              <el-select v-model="form.city" placeholder="请选择" @focus="randerSecondCityList">
                <el-option v-for="item,index in secondCityList" :key="index" :label="item" :value="item"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="方向" prop="direction">
              <el-select v-model="form.direction" placeholder="请选择" class="selects">
                <el-option v-for="item,index in direction" :key="index" :label="item" :value="item"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="题型">
              <el-radio-group v-model="form.questionType" @change="questionTypeChange">
                <el-radio v-for="item,index in questionType" :key="index" :label="item.value|capitalize">{{item.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="难度">
              <el-radio-group v-model="form.difficulty">
                <el-radio v-for="item,index in difficulty" :key="index" :label="item.value|capitalize">{{item.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="题干" prop="question">
               <editor
                  ref="editor"
                  api-key="q0wkqd8bi1hydscgnppsqe4knjbiubhy7708ge4wd60ur9tp"
                  v-model="form.question"
                  :init="{
                    height: 300,
                    menubar: false,
                    plugins: [
                      'advlist autolink lists link image charmap print preview anchor',
                      'searchreplace visualblocks code fullscreen',
                      'insertdatetime media table paste code help wordcount'
                    ],
                    toolbar:
                      'undo redo | formatselect | bold italic backcolor | \
                      alignleft aligncenter alignright alignjustify | \
                      bullist numlist outdent indent | removeformat | help'
                  }"
                />
            </el-form-item>
            <el-form-item label="选项" class="options myradio" v-if="form.questionType!=='3'">
              <!-- 单选 -->
              <el-radio-group v-model="options" @change="optionsChange"  v-if="form.questionType==='1'">

                <el-radio :label="item.code" v-for="item,index in form.options" :key="index">
                  <span>{{item.code}}:</span>
                  <el-input v-model="item.title" placeholder="请输入内容"></el-input>
                    <el-upload
                    list-type="picture-card"
                    class="avatar-uploader"
                    action="https://jsonplaceholder.typicode.com/posts/"
                    :show-file-list="false"
                    :on-success="((res,raw)=>{handleAvatarSuccess(res,raw,index)})"
                    :before-upload="beforeAvatarUpload">
                    <img v-if="form.options[index]['img']" :src="form.options[index]['img']" class="avatar">
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                  </el-upload>
                </el-radio>
              </el-radio-group>
              <!-- 多选 -->
              <el-checkbox-group v-model="checkList" v-if="form.questionType==='2'">
                  <el-checkbox :label="item.code" v-for="item,index in form.options" :key="index">
                    <span>{{item.code}}:</span>
                    <el-input v-model="item.title" placeholder="请输入内容"></el-input>
                    <el-upload
                      list-type="picture-card"
                      class="avatar-uploader"
                      action="https://jsonplaceholder.typicode.com/posts/"
                      :show-file-list="false"
                      :on-success="((res,raw)=>{handleAvatarSuccess(res,raw,index)})"
                      :before-upload="beforeAvatarUpload">
                      <img v-if="form.options[index]['img']" :src="form.options[index]['img']" class="avatar">
                      <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                  </el-checkbox>
                </el-checkbox-group>
                <!-- 增加选项 -->
                <el-form-item class="options">
                  <el-button v-if="isShow" @click="addOptions" ref="addOptions" :disabled="isflag" size="medium" type="danger">+增加选项与答案</el-button>
                </el-form-item>
            </el-form-item>
            <el-form-item label="解析视频"  class="selects">
              <el-input v-model="form.videoURL"></el-input>
            </el-form-item>
            <el-form-item label="答案解析" prop="answer">
              <editor
                  ref="editor"
                  api-key="q0wkqd8bi1hydscgnppsqe4knjbiubhy7708ge4wd60ur9tp"
                  v-model="form.answer"
                  :init="{
                    height: 300,
                    menubar: false,
                    plugins: [
                      'advlist autolink lists link image charmap print preview anchor',
                      'searchreplace visualblocks code fullscreen',
                      'insertdatetime media table paste code help wordcount'
                    ],
                    toolbar:
                      'undo redo | formatselect | bold italic backcolor | \
                      alignleft aligncenter alignright alignjustify | \
                      bullist numlist outdent indent | removeformat | help'
                  }"
                />
            </el-form-item>
            <el-form-item label="题目备注">
              <el-input type="textarea" v-model="form.remarks"  class="selects"></el-input>
            </el-form-item>
            <el-form-item label="试题标签">
              <el-select v-model="tags" placeholder="请选择试题标签" multiple  class="selects" @focus="getTagsList">
                <el-option v-for="item,index in tagsList" :key="index" :label="item.label" :value="item.label"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button :type="isUpData?'success':'primary'" @click="submit">确认提交</el-button>
            </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script>
// 导入富文本编辑器组件
import Editor from '@tinymce/tinymce-vue'
import { simple as subjectsSimple } from '@/api/hmmm/subjects'
import { simple as directorysSimple } from '@/api/hmmm/directorys'
import { list as companysList } from '@/api/hmmm/companys'
import { provinces, citys } from '@/api/hmmm/citys'
import { add as questionsAdd, update as questionsUpData } from '@/api/hmmm/questions'
import { difficulty, questionType, direction as directionList } from '@/api/hmmm/constants'
import { simple as tagsList } from '@/api/hmmm/tags'
export default {
  name: 'aaa',
  components: {
    editor: Editor
  },
  data () {
    return {
      form: {
        subjectID: null, // 学科
        catalogID: null, // 目录
        enterpriseID: null, // 企业
        province: null, // 城市
        city: null, // 地区
        direction: null, // 方向
        questionType: '1', // 题型
        difficulty: '1', // 难度
        question: '', // 题干
        options: [
          { code: 'A', title: '', img: null, isRight: 0 },
          { code: 'B', title: '', img: null, isRight: 0 },
          { code: 'C', title: '', img: null, isRight: 0 },
          { code: 'D', title: '', img: null, isRight: 0 }
        ], // 选项
        videoURL: null, // 解析视频
        answer: '', // 答案解析
        remarks: '', // 题目备注
        tags: '', // 试题标签
        isPerfect: null// 是否精选题  后台自动产生忽略

      },
      isUpData: false,
      subjectListEasy: [], // 学科列表
      directoryListEasy: [], // 目录简单列表
      allCompanysList: [], // 企业列表
      fistCityList: [], // 第城市一列表
      secondCityList: [], // 第二城市列表
      direction: [], // 方向
      questionType: questionType, // 题型
      difficulty: difficulty, // 难度
      isShow: true, // 点击简答按钮显示隐藏的表单
      options: null, // 单选时候的选项
      isflag: true, // 增加选项与答案按钮
      isShowChecked: null, // 多选按钮显示和隐藏
      checkList: [], // 多选列表
      tagsList: [], // 标签列表
      tags: null, // 标签
      rules: {
        subjectID: [
          { required: true, message: '请选择学科', trigger: 'change' }
        ],
        catalogID: [
          { required: true, message: '请选择目录', trigger: 'change' }
        ],
        enterpriseID: [
          { required: true, message: '请选择企业', trigger: 'change' }
        ],
        province: [
          { required: true, message: '请选择地区', trigger: 'change' }
        ],
        direction: [
          { required: true, message: '请选择方向', trigger: 'change' }
        ],
        question: [
          { required: true, message: '请输入题干', trigger: 'blur' }
        ],
        answer: [
          { required: true, message: '请输入题干', trigger: 'blur' }
        ]

      }

    }
  },
  created () {
    // console.log('this.$route.query: ', this.$route.query)
    this.getEditData()
    this.getSubjectList()
    this.getCompanysList()
    this.getDirectionLists()
    // this.getTagsList()
  },
  filters: {
    capitalize: function (value) {
      value = value.toString()
      return value
    }
  },
  watch: {
    options (val, oldVal) { // 普通的watch监听 单选
      console.log(111)
      if (this.form.questionType === '1') {
        this.form.options.forEach((item, index) => {
          item.isRight = 0
          if (item.code === this.options) {
            this.form.options[index].isRight = 1
          }
        })
      }
    },
    checkList (val, oldval) {
      // 如果是多选就执行
      if (this.form.questionType === '2') {
        // if (val.length === 0) {
        // } else {
        // 遍历多选列表
        this.form.options.forEach(item => {
          console.log('item: ', item)
          item.isRight = 0
          const isfind = this.checkList.find((obj) => { return obj === item.code })
          if (isfind) { item.isRight = 1 }
        })
        // }
      }
    },
    form: {
      immediate: true, // 立即执行
      deep: true, // 侦听复杂数据类型内的变化
      handler (newVal, oldVal) {
        if (this.form.questionType === '1') {
          this.form.options.forEach(item => {
            if (item.isRight === 1) { this.options = item.code }
          })
        }
      }
    }
  },
  methods: {
    // 上传图片
    handleAvatarSuccess (res, file, index) {
      // this.imageUrl = URL.createObjectURL(file.raw)
      this.form.options[index].img = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // 获取学科简单列表
    async getSubjectList () {
      const res = await subjectsSimple()
      // console.log('res: ', res)
      this.subjectListEasy = res.data
    },
    // 获取目录简单列表
    async getcatalog () {
      if (this.form.subjectID === null) return
      const res = await directorysSimple({ subjectID: this.form.subjectID })
      this.directoryListEasy = res.data
      // console.log('this.directoryListEasy: ', this.directoryListEasy)
    },
    // 获取企业列表
    async getCompanysList () {
      const query = {
        page: 1,
        pagesize: 10
      }
      const list = []
      const res = await companysList(query)
      while (res.data.counts + query.pagesize > query.page * query.pagesize) {
        const res = await companysList(query)
        query.page = query.page + 1
        list.push(...res.data.items)
      }
      // console.log(list)
      this.allCompanysList = list
    },
    // 第城市一列表
    randerFistCityList () {
      this.fistCityList = provinces()
    },
    // 地区列表
    randerSecondCityList (province) {
      if (this.form.province == null) return
      this.secondCityList = citys(this.form.province)
    },
    // 获取方向列表
    getDirectionLists () {
      this.direction = directionList
      // console.log('this.form.direction: ', this.direction)
      // console.log('directionList: ', directionList)
    },
    // 题型改变
    questionTypeChange () {
      if (this.form.questionType === '1') {
        this.isflag = true
      }
      if (this.form.questionType === '2') {
        this.isflag = false
      }
      if (this.form.questionType === '3') {
        this.isflag = true
      }
    },
    // 选项改变  可注释
    optionsChange () {
      if (this.form.questionType === '1') {
        this.form.options.forEach((item, index) => {
          item.isRight = 0
          if (item.code === this.options) {
            this.form.options[index].isRight = 1
          }
        })
      }
    },
    // 多选时候添加
    addOptions () {
      const obj = { code: null, title: null, img: null, isRight: 0 }
      let ask = this.form.options[this.form.options.length - 1].code.charCodeAt()
      ask++
      const transCode = String.fromCharCode(ask)
      obj.code = transCode
      this.form.options.push(obj)
    },
    // 获取标签列表
    async getTagsList () {
      // { id: this.form.subjectID }
      if (this.form.subjectID === null) return
      const res = await tagsList({ subjectID: this.form.subjectID })
      this.tagsList = res.data
      // console.log('res: ', res)
    },
    // 添加试题
    async addQuesrion () {
      // 判断tags的数据来决定是否上传this.form.tags
      // 如果select标签空的会把this.form的tags属性删除 否则添加上
      if (this.tags === [] || this.tags === null || this.tags === '' || this.tags.length === 0) {
        delete this.form.tags
      } else {
        this.form.tags = this.tags
      }
      const res = await questionsAdd(this.form)
      if (res.statusText === 'OK') {
        this.$message({
          message: '添加成功',
          type: 'success'
        })
      }
      this.resetForm()
      this.tags = null
      this.$router.push({ path: 'list' })
      // console.log('res: ', res)
    },
    // 表单提交
    submit () {
      // 表单的整体校验
      this.$refs.form.validate((valid) => {
        if (valid) {
          // 判断是修改还是提交
          if (!this.isUpData) {
            // 如果isUpData是false的话 就是提交
            this.addQuesrion()
          } else {
            this.upDataQuesrion()
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 修改试题
    async upDataQuesrion () {
      // 判断tags的数据来决定是否上传this.form.tags
      // 如果select标签空的会把this.form的tags属性删除 否则添加上
      if (this.tags === [] || this.tags === null || this.tags === '' || this.tags.length === 0) {
        delete this.form.tags
      } else {
        this.form.tags = this.tags
      }
      // 发送axios...
      const res = await questionsUpData(this.form)
      if (!res.statusText === 'OK') {
        this.$message.error('修改失败')
      }
      this.$message.success('修改成功')
      this.$router.push({ path: 'list' })
    },
    // 清空表单方法
    resetForm () {
      this.form.answer = ''
      this.form = {
        subjectID: null, // 学科
        catalogID: null, // 目录
        enterpriseID: null, // 企业
        province: null, // 城市
        city: null, // 地区
        direction: null, // 方向
        questionType: '1', // 题型
        difficulty: '1', // 难度
        question: '', // 题干
        options: [
          { code: 'A', title: '', img: null, isRight: 0 },
          { code: 'B', title: '', img: null, isRight: 0 },
          { code: 'C', title: '', img: null, isRight: 0 },
          { code: 'D', title: '', img: null, isRight: 0 }
        ], // 选项
        videoURL: null, // 解析视频
        answer: '', // 答案解析
        remarks: '', // 题目备注
        tags: '', // 试题标签
        isPerfect: null// 是否精选题  后台自动产生忽略

      }
      this.$refs.form.resetFields()
      this.form.question = ''
    },
    // 获取路由数据
    getEditData () {
      if (this.$route.query.isUpData) {
        this.isUpData = true
        this.form = this.$route.query.data
      }
      if (this.form.questionType === '2') {
        const arr = []
        this.form.options.forEach(item => {
          if (item.isRight === 1) { arr.push(item.code) }
        })
        this.checkList = arr
      }
    }
  }

}
</script>

<style lang="scss" scoped>
// 选择表单样式
.selects{
  width: 400px;
}
.cityselect{
  .el-select{
    width: 195px;
    margin-right: 10px;
  }
}
// 选项
.options .el-radio-group .el-radio{
  margin: 10px;
}
.options span {
  margin-right: 8px;
}
.options .el-input{
  margin-right: 5px;
}
// 图片上传组件样式
 .avatar-uploader{
   width: 100px;
   display: inline-block;
 }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .el-upload {
     border: 1px dashed #d9d9d9;
     height: 10px !important
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 18px;
    color: #8c939d;
    width: 100px;
    height: 55px;
    line-height: 55px;
    text-align: center;
  }
  .avatar {
    width: 100px;
    height: 55px;
    display: block;
  }
  ::v-deep .el-upload--picture-card {
    width: 100px;
    height: 55px;
    line-height: 55px;
    vertical-align: middle;
  }
  // radio单选
  .myradio .el-radio{
    display: block;
  }
  .el-checkbox{
    display: block;
    margin: 10px;
  }

</style>
